<!--
 * @copyright 2025 银杏ERP
 * @author 银杏ERP
 * @version 1.0
 * @license http://www.hhyx.xyz
 * @developer Lhf
-->

<template>
  <div class="customer-analysis-chart">
    <div ref="chartRef" class="chart-container" v-loading="loading"></div>
    <div v-if="loading" class="loading-placeholder">
      <el-skeleton :rows="5" animated />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick, defineProps, PropType, onUnmounted } from 'vue'
import * as echarts from 'echarts/core'
import { PieChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent
} from 'echarts/components'
import { LabelLayout, UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'

// 注册 ECharts 组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  PieChart,
  BarChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
])

// 定义图表数据类型
interface ChartDataItem {
  name: string
  value: number
}

interface ChartDataType {
  sales: ChartDataItem[]
  type: ChartDataItem[]
  region: ChartDataItem[]
}

const props = defineProps({
  analysisType: {
    type: String as PropType<'sales' | 'type' | 'region'>,
    required: true,
    default: 'sales'
  },
  chartData: {
    type: Object as PropType<ChartDataType>,
    required: true
  }
})

const chartRef = ref<HTMLElement | null>(null)
const loading = ref(true)
let chart: echarts.ECharts | null = null

// 获取渐变颜色
const getGradientColors = (type: string) => {
  if (type === 'sales') {
    return [
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#3699FF' },
        { offset: 1, color: '#2878F0' }
      ]),
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#FF9966' },
        { offset: 1, color: '#FF5E62' }
      ]),
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#56ab2f' },
        { offset: 1, color: '#a8e063' }
      ]),
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#8E2DE2' },
        { offset: 1, color: '#4A00E0' }
      ])
    ]
  } else if (type === 'type') {
    return [
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#36D1DC' },
        { offset: 1, color: '#5B86E5' }
      ]),
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#FF9966' },
        { offset: 1, color: '#FF5E62' }
      ]),
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#F9D423' },
        { offset: 1, color: '#FF4E50' }
      ]),
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#DCE35B' },
        { offset: 1, color: '#45B649' }
      ])
    ]
  } else {
    // 区域分布用更多颜色
    return [
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#36D1DC' },
        { offset: 1, color: '#5B86E5' }
      ]),
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#FF9966' },
        { offset: 1, color: '#FF5E62' }
      ]),
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#56ab2f' },
        { offset: 1, color: '#a8e063' }
      ]),
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#f2709c' },
        { offset: 1, color: '#ff9472' }
      ]),
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#4facfe' },
        { offset: 1, color: '#00f2fe' }
      ]),
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#fad0c4' },
        { offset: 1, color: '#f1a7f1' }
      ])
    ]
  }
}

// 获取图表标题
const getChartTitle = (type: string): string => {
  const titles: Record<string, string> = {
    'sales': '客户销售额分布',
    'type': '客户类型分布',
    'region': '客户区域分布'
  }
  return titles[type] || '客户分析'
}

// 获取图表副标题
const getChartSubtitle = (type: string): string => {
  const subtitles: Record<string, string> = {
    'sales': '按销售额占比分析',
    'type': '按客户类型分析',
    'region': '按地区分布分析'
  }
  return subtitles[type] || ''
}

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return
  loading.value = true
  
  if (chart) {
    chart.dispose()
  }
  
  // 创建图表实例
  chart = echarts.init(chartRef.value)
  
  // 获取当前类型的数据
  const currentData = props.chartData[props.analysisType] || []
  const gradientColors = getGradientColors(props.analysisType)
  
  // 根据分析类型选择不同的图表
  let option: echarts.EChartsOption
  
  if (props.analysisType === 'region') {
    // 区域分布用柱状图
    option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: (params: any) => {
          const data = params[0]
          return `${data.name}: ${data.value} (${data.percent}%)`
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: currentData.map(item => item.name),
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        }
      },
      series: [
        {
          name: '区域分布',
          type: 'bar',
          data: currentData.map((item, index) => {
            const sum = currentData.reduce((acc, curr) => acc + curr.value, 0)
            const percent = ((item.value / sum) * 100).toFixed(1)
            
            return {
              value: item.value,
              name: item.name,
              percent: percent,
              itemStyle: {
                color: gradientColors[index % gradientColors.length]
              }
            }
          }),
          barWidth: '50%',
          showBackground: true,
          backgroundStyle: {
            color: 'rgba(180, 180, 180, 0.1)'
          },
          label: {
            show: true,
            position: 'top',
            formatter: '{c}%'
          }
        }
      ]
    }
  } else {
    // 销售额分布和客户类型用饼图
    option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        top: 'center',
        itemWidth: 10,
        itemHeight: 10,
        icon: 'circle',
        formatter: (name: string) => {
          const item = currentData.find(i => i.name === name)
          const total = currentData.reduce((sum, i) => sum + i.value, 0)
          const percent = item ? ((item.value / total) * 100).toFixed(1) : '0.0'
          return `${name}  ${percent}%`
        }
      },
      series: [
        {
          name: getChartTitle(props.analysisType),
          type: 'pie',
          radius: ['45%', '75%'],
          center: ['65%', '50%'],
          avoidLabelOverlap: true,
          itemStyle: {
            borderRadius: 6,
            borderColor: '#fff',
            borderWidth: 1
          },
          label: {
            show: false
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '14',
              fontWeight: 'bold'
            },
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          labelLine: {
            show: false
          },
          data: currentData.map((item, index) => ({
            value: item.value,
            name: item.name,
            itemStyle: {
              color: gradientColors[index % gradientColors.length]
            }
          }))
        }
      ]
    }
  }
  
  // 设置图表配置
  chart.setOption(option)
  loading.value = false
}

// 窗口大小变化时重绘图表
const handleResize = () => {
  chart?.resize()
}

// 监听分析类型变化
watch(() => props.analysisType, () => {
  nextTick(() => {
    initChart()
  })
})

// 监听图表数据变化
watch(() => props.chartData, () => {
  nextTick(() => {
    initChart()
  })
}, { deep: true })

// 组件挂载完成后初始化图表
onMounted(() => {
  nextTick(() => {
    initChart()
    window.addEventListener('resize', handleResize)
  })
})

// 组件卸载前清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  chart?.dispose()
})
</script>

<style scoped lang="scss">
.customer-analysis-chart {
  width: 100%;
  height: 100%;
  position: relative;
  
  .chart-container {
    width: 100%;
    height: 100%;
    min-height: 220px;
  }
  
  .loading-placeholder {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(255, 255, 255, 0.8);
  }
}
</style> 